package cn.xtits.xtf.common.utils;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;

/**
 * Created by ShengHaiJiang on 2017/3/16.
 */
public class JwtUtil {
    private final static String DEFAULT_KEY = "xtf+d06ed21a41cd6ff5+85609984d06ed21a41cd6ff5bb1edf94";

    // 加密密文，私钥
    public static final String JWT_SECRET = "shenghaijiang.com";

    // 由字符串生成加密key
    public static SecretKey generalKey() {
        try {
            byte[] encodedKey = Base64.getEncoder().encode(JWT_SECRET.getBytes("utf-8"));
            // 根据给定的字节数组使用AES加密算法构造一个密钥
            SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
            return key;
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * 创建jwt
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public static String createJWT(String id, String subject, long ttlMillis) throws Exception {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 解密jwt
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception{
        SecretKey key = generalKey();
        Claims claims = Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwt).getBody();
        return claims;
    }

//    /**
//     * 生成subject信息
//     * @param user
//     * @return
//     */
//    public static String generalSubject(t_user user){
//        JSONObject jo = new JSONObject();
//        jo.put("userId", user.getId());
//        jo.put("mobile", user.getMobile());
//        return jo.toJSONString();
//    }
}
